<?php
namespace App\Repos;

use App\Models\Billboard;
use App\Models\BillboardPic;
use App\Services\RedisService;

class BillboardRepo 
{
    public static function get($where=[])
    {
    	return Billboard::where($where)->get();
    }

    public static function pages($where=[],$fields=['*'],$num=10)
    {
    	$query = Billboard::query();
        if(array_get($where,'code')){
            $code = array_pull($where,'code');
            $query->where('code','like','%'.$code.'%');
        }
        $list = $query->where($where)
    						->select($fields)
                            ->orderBy('id','desc')
    						->paginate($num);
    	return $list;					
    }

    public static function find($where=[],$fields=['*'])
    {     
     
        return Billboard::where($where)->first();    
        
    }

    public static function save($data)
    {
        $pics = array_pull($data,'pics');
        $pics = explode(',', rtrim($pics,','));
        if($pics) {
            $data['thumb'] = $pics[0];
        }
        $flag   = Billboard::create($data);
        if($flag) {
            $key = 'ad:board:'.$flag->id;  
            RedisService::set($key,$flag->toJson());
        }

        
        foreach ($pics as $k => $v) {


            $bp['billboard_id'] = $flag->id;
            $bp['pic'] = $v;

            BillboardPic::create($bp);
        }
        
        $lnglat = explode(',', $data['lnglat']);
        RedisService::geoadd($lnglat[0],$lnglat[1],$flag->id);
        return $flag;
    }

    public static function update($id,$data)
    {
       $pics = array_pull($data,'pics');
       $pics = explode(',', rtrim($pics,','));
       $flag   =  Billboard::where(['id'=>$id])->update($data);
       if($flag) {
        foreach ($pics as $k => $v) {


            $bp['billboard_id'] = $id;
            $bp['pic'] = $v;

            BillboardPic::create($bp);
        }

            $key = 'ad:board:'.$id;  
            $data['id'] = $id;
            $flag = RedisService::set($key,json_encode($data));
        }
       $lnglat = explode(',', $data['lnglat']);
       RedisService::geoadd($lnglat[0],$lnglat[1],$id);
       return $flag;
    }

    public static function delete($id)
    {
        $flag = Billboard::destroy($id);
        RedisService::geodel($id);
        return $flag;
    }

    public static function rank()
    {
        return ['AAA级'=>'AAA级','AAAA级'=>'AAAA级','AAAAA级'=>'AAAAA级'];
    }

    public static function pics($billboard_id)
    {
        return BillboardPic::where('billboard_id',$billboard_id)->get();
    }
}
